package com.begamer.card.controller;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.cache.PlayerInfo;
import com.begamer.card.common.util.Random;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.Statics;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.ImaginationData;
import com.begamer.card.common.util.binRead.ImaginationcomposeData;
import com.begamer.card.common.util.binRead.ImaginationdropData;
import com.begamer.card.common.util.binRead.ItemsData;
import com.begamer.card.common.util.binRead.MeditationData;
import com.begamer.card.json.PackElement;
import com.begamer.card.json.command2.ImaginationClearJson;
import com.begamer.card.json.command2.ImaginationClearResultJson;
import com.begamer.card.json.command2.ImaginationClickJson;
import com.begamer.card.json.command2.ImaginationClickResultJson;
import com.begamer.card.json.command2.ImaginationComposeJson;
import com.begamer.card.json.command2.ImaginationComposeResultJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.PlayerLogger;
import com.begamer.card.model.pojo.Item;

public class ImaginationController extends AbstractMultiActionController
{
	private static final Logger logger=Logger.getLogger(BattleReadyController.class);
 	private static Logger playlogger =PlayerLogger.logger;
 	private static Logger errorlogger = ErrorLogger.logger;
 	
 	/**点击冥想获得物品**/
	public ModelAndView imaginationClick(HttpServletRequest request ,HttpServletResponse response)
	{
		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			//获取参数
			ImaginationClickJson icj =JSONObject.toJavaObject(jsonObject, ImaginationClickJson.class);
			ImaginationClickResultJson icrj =new ImaginationClickResultJson();
			if(icj !=null)
			{
				PlayerInfo pi =Cache.getInstance().getPlayerInfo(icj.playerId, request.getSession());
				if(pi !=null)
				{
					int errorcode =0;
					int nId =icj.id;
					int npcId =1;
					//当前npc
					ImaginationData iData = null;
					//判断是否存在下一个NPC并且是否可以激活
					ImaginationData imaginationData = null;
					if (nId != -1)
					{
						iData = ImaginationData.getImaginationData(nId);
						imaginationData = ImaginationData.getImaginationData(nId+1);
						if(iData !=null)
						{
							if(imaginationData !=null)
							{
								if(pi.player.getNewPlayerType()==24 && npcId==1)//新手灵界，第二个npc必激活
								{
									npcId =imaginationData.index;
								}
								else
								{
									int randnum =Random.getNumber(0, 1000);
									if(randnum>0 && randnum<=iData.probability)
									{
										npcId =imaginationData.index;
									}
								}
							}
							//校验金币
							if(pi.player.getGold()<iData.spend)
							{
								errorcode =19;
							}
							//校验任务是否完成
							if (pi.player.getMid() > 0 && pi.player.getMnum() >= 0)
							{
								MeditationData mData = MeditationData.getData(pi.player.getMid());
								if (mData.timeNumber == pi.player.getMnum())
								{
									errorcode = 131;
								}
							}
						}
						else
						{
							errorcode =44;
						}
					}
					else
					{
						//校验领奖
						if (pi.player.getMid() > 0 && pi.player.getMnum() >= 0)
						{
							MeditationData mData = MeditationData.getData(pi.player.getMid());
							if (mData.timeNumber != pi.player.getMnum())
							{
								errorcode = 132;
							}
						}
						else
						{
							errorcode = 132;
						}
					}
					//功能阶段
					if(errorcode ==0)
					{
						if (icj.id == -1)//领冥想任务奖励
						{
							int mid = pi.player.getMid();
							MeditationData mdData = MeditationData.getData(mid);
							int roll = Random.getNumber(100);
							String[] rewards = mdData.rewards.split("&");
							if (roll>= StringUtil.getInt(rewards[3]))
							{
								pi.addItem(mdData.itemID, StringUtil.getInt(rewards[0]));
							}
							else
							{
								pi.addItem(mdData.itemID, StringUtil.getInt(rewards[2]));
							}
							int mrandom = pi.player.getMrandom();
							if (mrandom>0)
							{
								MeditationData mData = MeditationData.getData(mrandom);
								pi.player.setMid(mrandom);
								pi.player.setMnum(0);
								pi.player.setMrandom(mData.random);
							}
							if (mrandom<0)
							{
								MeditationData mData = MeditationData.getMeditationDataByRandom(mrandom);
								int id = Random.getNumber((mData.id + 1), MeditationData.getDatas().size());
								pi.player.setMid(id);
								pi.player.setMnum(0);
							}
							icrj.id = pi.player.getImagination();
							icrj.g = pi.player.getGold();
							icrj.mid = pi.player.getMid();
							icrj.mnum = pi.player.getMnum();
							icrj.s = 200+"";
							playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|点击领取冥想任务奖励");
						}
						else
						{
							//记录每日任务进度
							ActivityController.updateTaskComplete(10, pi, 1);
							pi.player.addActive(10,1);
							pi.player.setImagination(npcId);
							icrj.id =npcId;
							//金币消耗
							pi.player.removeGold(iData.spend);
							//记录冥想任务次数
							pi.player.setMnum(pi.player.getMnum() + 1);
							//掉落物品
							int number =Random.getNumber(0,10000);
							List<String> sInfo =new ArrayList<String>();
							for(int j=0;j<iData.item_info.size();j++)
							{
								sInfo.add(iData.item_info.get(j));
							}
							int start =0;
							if(sInfo !=null && sInfo.size()>0)
							{
								for(int k=0;k<sInfo.size();k++)
								{
									if(sInfo.get(k)==null || sInfo.get(k).length()==0)
									{
										continue;
									}
									else
									{
										
										String [] str =sInfo.get(k).split("-");//type-level-id-pro
										if(pi.player.getLevel()>=StringUtil.getInt(str[1]))
										{
											if(StringUtil.getInt(str[1])>0)
											{
												//用前边物品出现的几率去缩减最后一个物品的几率
												int pro =StringUtil.getInt(str[3]);
												for(int i=sInfo.size()-1;i>=0;i--)
												{
													if(pro>0)
													{
														if(sInfo.get(i)!=null && sInfo.get(i).length()>0)
														{
															String [] temp =sInfo.get(i).split("-");
															if(StringUtil.getInt(temp[3])>pro)
															{
																int n =StringUtil.getInt(temp[3])-pro;
																sInfo.set(i, temp[0]+"-"+temp[1]+"-"+temp[2]+"-"+n);
																pro =0;
															}
															else if(StringUtil.getInt(temp[3])==pro)
															{
																sInfo.set(i,"");
																pro=0;
															}
															else
															{
																sInfo.set(i, "");
																pro =pro-StringUtil.getInt(temp[3]);
															}
														}
														else
														{
															sInfo.set(i, "");
														}
													}
													else
													{
														break;
													}
												}
											}
											int end =Integer.parseInt(str[3])+start;
											if(number >=start && number<end)
											{
												if(Integer.parseInt(str[0])==2 || Integer.parseInt(str[0])==1)//被动技能2或者炉灰1随机产生
												{
													int num =Random.getNumber(0, 1000);
													List<ImaginationdropData> drops =ImaginationdropData.getRandomDropData(Integer.parseInt(str[2]));
													int t =0;
													for(int j=0;j<drops.size();j++)
													{
														int d =t+drops.get(j).probability;
														if(num>=t && num<=d)
														{
															icrj.s =str[0]+"-"+drops.get(j).skillID;
															break;
														}
														else
														{
															t = d;
														}
													}
												}
												else//碎片3
												{
													icrj.s =str[0]+"-"+str[2];
												}
												break;
											}
											else
											{
												start =end;
											}
										}
										else
										{
											continue;
										}
									}
								}
							}
							icrj.g =pi.player.getGold();
							icrj.mid = pi.player.getMid();
							icrj.mnum = pi.player.getMnum();
							if(pi.player.getNewPlayerType()==24)//新手灵界
							{
								pi.player.setNewPlayerType(pi.player.getNewPlayerType()+1);
							}
							playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|点击冥想获得物品");
						}
					}
					else
					{
						icrj.errorCode =errorcode;
					}
				}
				else
				{
					icrj.errorCode =-3;
				}
			}
			else
			{
				icrj.errorCode =-1;
			}
			Cache.recordRequestNum(icrj);
			String msg =JSON.toJSONString(icrj);
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e) 
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/**冥想一键处理**/
	public ModelAndView imaginationClear(HttpServletRequest request ,HttpServletResponse response)
	{
		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			//获取参数
			ImaginationClearJson icj =JSON.toJavaObject(jsonObject, ImaginationClearJson.class);
			ImaginationClearResultJson icrj =new ImaginationClearResultJson();
			if(icj !=null)
			{
				PlayerInfo pi =Cache.getInstance().getPlayerInfo(icj.playerId, request.getSession());
				if(pi !=null)
				{
					//校验类型
					int errorcode =0;
					List<String> list =icj.s;
					for(int k=0;k<list.size();k++)
					{
						String [] str =list.get(k).split("-");
						if(Integer.parseInt(str[0])<0 || Integer.parseInt(str[0])>3)
						{
							errorcode =32;
						}
					}
					//功能阶段
					if(errorcode ==0)
					{
						int gold=0;
						for(int k=0;k<list.size();k++)
						{
							String [] str =list.get(k).split("-");
							if(Integer.parseInt(str[0])==1)//炉灰
							{
								ItemsData item =ItemsData.getItemsData(Integer.parseInt(str[1]));
								gold +=item.sell*Integer.parseInt(str[2]);
							}
							else if(Integer.parseInt(str[0])==2)//passiveskill放入背包
							{
								for(int j=0;j<Integer.parseInt(str[2]);j++)
								{
									pi.addPassiveSkill(Integer.parseInt(str[1]));
								}
							}
							else if(Integer.parseInt(str[0])==3)//item放入背包
							{
								pi.addItem(Integer.parseInt(str[1]), Integer.parseInt(str[2]));
							}
						}
						icrj.gold =gold;
						pi.player.addGold(gold);
						//背包容量
						int packageNum=Statics.getPackageNum(pi);
						if(pi.getPassiveSkillls().size()>=packageNum)
						{
							icrj.i =0;
						}
						else
						{
							icrj.i =packageNum-pi.getPassiveSkillls().size();
						}
						if(icj.t==2)//兑换按钮，需碎片信息
						{
							List<PackElement> pes =UiController.getElements(pi, 5);
							List<PackElement> s =new ArrayList<PackElement>();
							for(PackElement p :pes)
							{
								ItemsData iData =ItemsData.getItemsData(p.getDataId());
								if(iData.type ==3)//冥想产物
								{
									p.setPile(pi.getTargetItemsNum(p.getDataId()));
									s.add(p);
								}
							}
							icrj.s =s;
						}
						icrj.g =pi.player.getGold();
						playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|冥想一键处理");
					}
					else
					{
						icrj.errorCode =errorcode;
					}
				}
				else
				{
					icrj.errorCode =-3;
				}
			}
			else
			{
				icrj.errorCode=-1;
			}
			Cache.recordRequestNum(icrj);
			String msg =JSON.toJSONString(icrj);
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e) 
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	/**冥想兑换物品**/
	public ModelAndView imaginationCompose(HttpServletRequest request ,HttpServletResponse response)
	{
		try{
			//检验密钥
			ModelAndView checkResult = RequestUtil.check(request);
			if(checkResult != null)
			{
				return checkResult;
			}
			//获取json
			JSONObject jsonObject = RequestUtil.getJsonObject(request);
			//获取参数
			ImaginationComposeJson icj =JSONObject.toJavaObject(jsonObject, ImaginationComposeJson.class);
			ImaginationComposeResultJson icrj =new ImaginationComposeResultJson();
			if(icj != null)
			{
				PlayerInfo pi =Cache.getInstance().getPlayerInfo(icj.playerId, request.getSession());
				if(pi != null)
				{
					int errorcode =0;
					//兑换物品id
					ImaginationcomposeData icData =ImaginationcomposeData.getImaginationcomposeData(icj.id);
					//校验阶段
					//校验材料是否足够
					if(icData !=null)
					{
						int material =icData.material1;
						int number =icData.number1;
						List<Item> items =pi.getTargetItems(material);
						if(items !=null && items.size()>0)
						{
							int pile=pi.getTargetItemsNum(material);
							if(pile<number)
							{
								errorcode =20;
							}
						}
						else
						{
							errorcode =20;
						}
					}
					else
					{
						errorlogger.error("icj.id:"+icj.id);
						errorcode =21;
					}
					if(errorcode == 0)
					{
						int packageNum=Statics.getPackageNum(pi);
						if(icData.type==1 && pi.getCards().size()>=packageNum)
						{
							errorcode =53;
						}
						else if(icData.type ==2 && pi.getEquips().size()>=packageNum)
						{
							errorcode =53;
						}
						else if(icData.type ==3 && pi.getItems().size()>=packageNum)
						{
							errorcode =53;
						}
						else if(icData.type==4 && pi.getPassiveSkillls().size()>=packageNum)
						{
							errorcode =53;
						}
					}
					
					//功能阶段
					if(errorcode == 0)
					{
						List<Integer> cardIds =new ArrayList<Integer>();
						int material =icData.material1;
						int number =icData.number1;
						pi.removeItem(material, number);
						//将兑换物品加入背包
						int type =icData.type;
						switch (type)
						{
						case 1://card
							cardIds.add(icData.composite);
							pi.addCard(icData.composite, 1);
							break;
						case 2://equip
							pi.addEquip(icData.composite);
							break;
						case 3://item
							pi.addItem(icData.composite, 1);
							break;
						case 4://passiveskill
							pi.addPassiveSkill(icData.composite);
							break;
						}
						if(cardIds.size()>0)
						{
							pi.getNewUnitSkill(cardIds);
						}
						icrj.id =icj.id;
						//碎片
						List<PackElement> pes =UiController.getElements(pi, 5);
						List<PackElement> s =new ArrayList<PackElement>();
						for(PackElement p :pes)
						{
							ItemsData iData =ItemsData.getItemsData(p.getDataId());
							if(iData.type ==3)
							{
								s.add(p);
							}
						}
						icrj.s =s;
						playlogger.info("|区服："+Cache.getInstance().serverId+"|玩家："+pi.player.getId()+"|"+pi.player.getName()+"|等级："+pi.player.getLevel()+"|冥想兑换物品");
					}
					else
					{
						icrj.errorCode =errorcode;
					}
				}
				else
				{
					icrj.errorCode =-3;
				}
			}
			else
			{
				icrj.errorCode =-1;
			}
			Cache.recordRequestNum(icrj);
			String msg =JSON.toJSONString(icrj);
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName()+"->"+Thread.currentThread().getStackTrace()[1].getMethodName()+"():",e);
			RequestUtil.removeKey(request);
			String newKey = RequestUtil.setNewKey(request);
			RequestUtil.setResult(request, newKey);
		}
		return new ModelAndView("/user/result.vm");
	}
}
